package uestc.lj.midPromotion.macro;

/**
 * @Author:Crazlee
 * @Date:2021/12/2
 */
public class Code04_ConvertStringToInteger {
	public static int convert(String str) {
		// can not convert
		if (str == null || str.equals("")) {
			return 0;
		}
		char[] chas = str.toCharArray();

		// can not convert
		if (!isValid(chas)) {
			return 0;
		}
		//判断是不是负数，true表示不是负数
		boolean posi = chas[0] != '-';
		int minq = Integer.MIN_VALUE / 10;
		int minr = Integer.MIN_VALUE % 10;
		int res = 0;
		int cur = 0;
		//如果是负数要从下标1开始，如果不是负数要从下标0开始
		for (int i = posi ? 0 : 1; i < chas.length; i++) {
			//利用负数来转换
			cur = '0' - chas[i];
			// 中途转换过程中溢出
			if ((res < minq) || (res == minq && cur < minr)) {
				return 0;
			}
			res = res * 10 + cur;
		}

		// can not convert
		if (posi && res == Integer.MIN_VALUE) {
			return 0;
		}
		return posi ? -res : res;
	}

	public static boolean isValid(char[] chas) {
		if (chas[0] != '-' && (chas[0] < '0' || chas[0] > '9')) {
			return false;
		}
		if (chas[0] == '-' && (chas.length == 1 || chas[1] == '0')) {
			return false;
		}
		if (chas[0] == '0' && chas.length > 1) {
			return false;
		}
		for (int i = 1; i < chas.length; i++) {
			if (chas[i] < '0' || chas[i] > '9') {
				return false;
			}
		}
		return true;
	}

	public static void main(String[] args) {
		// max in java
		String test1 = "2147483647";
		System.out.println(convert(test1));

		// min in java
		String test2 = "-2147483648";
		System.out.println(convert(test2));

		// overflow
		String test3 = "2147483648";
		System.out.println(convert(test3));

		// overflow
		String test4 = "-2147483649";
		System.out.println(convert(test4));

		String test5 = "-123";
		System.out.println(convert(test5));

	}

}

